//
//  SigninViewModel.swift
//  JLDiaryApp
//
//  Created by Jiang Chencheng on 2024/9/27.
//

import Foundation
import SwiftUI

class SigninViewModel: ObservableObject {
    
    @Published var email = ""
    
    @Published var password = ""
    
    @Published var isLoading = false
    
    @Published var isError = false
    
    var toastTitle: String = ""

    var user: UserCenter?
}

extension SigninViewModel {
    
    func setup(_ user: UserCenter) {
        self.user = user
    }
    
    
    func signin()  {
        
        
        guard email.isEmail else {
            isError = true
            toastTitle = "Invalid email"
            return
        }
        
        guard password.isPasswordValid else {
            isError = true
            toastTitle = "Invalid password, the letters and numbers with minimum 8 lengths"
            return
        }
        
        Task {
            do {
                isLoading = true
                try await user?.signin(email: email, password: password)
                isLoading = false
            }catch {
                isLoading = false
                toastTitle = error.localizedDescription
                isError = true
            }
        }
        
        
    }
    
}

